import 'package:bwt_ad_flutter/ad/BwtNativeExpressAd.dart';
import 'package:bwt_ad_flutter/ad/widget/BwtNativeExpressAdWidget.dart';
import 'package:flutter/cupertino.dart';

import '../../BwtAdCore.dart';
import 'BwtAdLoader.dart';

class BwtNativeExpressAdLoader extends BwtAdLoader<BwtNativeExpressAd> {
  /// 加载广告
  loadAd({
    required String posId,
    required double adWidth,
  }) {
    load(
      posId: posId,
      methodName: BwtAdCore.methodLoadNativeExpressAd,
      arguments: {BwtAdCore.keyAdWidth: adWidth},
    );
  }

  @override
  BwtNativeExpressAd createBwtAd({
    required String adId,
    required Map<String, dynamic>? arguments,
  }) {
    return BwtNativeExpressAd(
      adId: adId,
      adLoaderId: adLoaderId,
      adWidth: arguments?[BwtAdCore.keyAdWidth] ?? double.infinity,
    );
  }

  @override
  onAdLoadCallback(BwtNativeExpressAd bwtAd) {
    bwtAd.globalKey = GlobalKey();
    bwtAd.expressAd = BwtNativeExpressAdWidget(
      key: bwtAd.globalKey,
      bwtExpressAd: bwtAd,
    );
    return super.onAdLoadCallback(bwtAd);
  }

  @override
  onAdCloseCallback(BwtNativeExpressAd bwtAd) {
    if (bwtAd.refreshAdClosed()) {
      _checkUpdateWidget(bwtAd);
    }
    return super.onAdCloseCallback(bwtAd);
  }

  /// 广告视图测量回调
  onAdMeasured(BwtNativeExpressAd bwtAd, double width, double height) {
    if (bwtAd.refreshAdHeight(height)) {
      _checkUpdateWidget(bwtAd);
    }
  }

  /// 尝试更新广告视图
  void _checkUpdateWidget(BwtNativeExpressAd bwtAd) {
    var mounted = bwtAd.globalKey?.currentState?.mounted ?? false;
    if (mounted) {
      bwtAd.globalKey?.currentState?.update();
    }
  }
}
